package com.example.controller;
import com.example.bean.LoginLog;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity; //added 26/11/24 for userInfoResponse
import org.springframework.web.bind.annotation.*;
import com.example.dao.UserDaoImpl;

import com.example.dao.LoginLogRepository;

import com.example.bean.UserBean;
import org.springframework.web.util.HtmlUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class UserController {
    @Autowired
    private UserDaoImpl userDaoImpl;

    @Autowired
    private LoginLogRepository loginLogRepository;

    @RequestMapping(value = "api/login",method = RequestMethod.POST)
    @ResponseBody
    public boolean login(HttpServletResponse response, @RequestBody UserBean requestUser)
    {
        String username = requestUser.getUsername();
        String password = requestUser.getPassword();
        username = HtmlUtils.htmlEscape(username);
        password = HtmlUtils.htmlEscape(password);
        List<UserBean> users = userDaoImpl.findByUserName(username);
        if(users.size()==0) return  false;
        UserBean user = users.get(0);
        System.out.println("Login user: " + user.getUsername());
        //System.out.println(password);
        //System.out.println("Login user: "user.getUsername()+" "+user.getPassword());


        //java.util.Date 上传数据库至MySQL中datetime类型，目前没有出现报错（可能是系统自动把java和mysql的时间数据类型做了格式转换）
        //如有问题可以参考https://blog.csdn.net/m0_37642480/article/details/116241931解决
        //或者看方法调用的描述文档https://www.runoob.com/java/java-date-time.html
        //java.util.Date format: Thu Nov 28 17:55:51 CST 2024 -> present in mysql form:2024-11-28 17:47:09
        //mysql datetime format: 2024-11-27 00:57:48 -> presented in java form:2024-11-27T20:07:50.000+00:00
        loginLogRepository.insertLoginLog(username, new Date());
        System.out.println("Login Log recorder: at time "+ new Date());

        // 登录增加经验
        userDaoImpl.levelUp(username);


        return password.equals(user.getPassword());
    }

    @PostMapping("api/register")
    @ResponseBody
    public boolean register(HttpServletResponse response, @RequestBody UserBean requestUser)
    {
        boolean flag = userDaoImpl.addUser(requestUser);
        return flag;
    }

    //获得用户信息
    @GetMapping("api/me/space")
    @ResponseBody
    public ResponseEntity<UserBean> mespaceGet(@RequestParam String username) {
        if (username == null || username.isEmpty()) {
            return ResponseEntity.badRequest().body(null); // 返回400状态码，表示请求参数不正确
        }
        List<UserBean> users = userDaoImpl.findByUserName(username);
        if (users.isEmpty()) {
            return ResponseEntity.notFound().build(); // 返回404状态码，表示用户未找到
        }
        UserBean existingUser = users.get(0); // 获取列表中的第一个用户对象
        return ResponseEntity.ok(existingUser); // 返回200状态码，表示请求成功
    }

    @PutMapping("api/me/space")
    public ResponseEntity<UserBean> mespacePost(@RequestBody Map<String, Object> data) {
        String username = (String) data.get("username");
        String email = (String) data.get("email");
        String password = (String) data.get("password");
        String tel = (String) data.get("tel");

        System.out.println("Updated info of user: "+username);
        System.out.println(email);
        System.out.println(password);
        System.out.println(tel);
        boolean flag = userDaoImpl.updateUserInfo(username, email, tel, password);
        if (flag) {
            return ResponseEntity.ok(userDaoImpl.findByUserName(username).get(0));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

}
